package com.lyy.lottery.service.impl;

import com.lyy.lottery.common.errorcode.ServiceErrorCodeConstants;
import com.lyy.lottery.common.exception.ServiceException;
import com.lyy.lottery.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
public class PictureServiceImpl implements PictureService {

    @Value("${pic.local-path}")
    private String localPath;

    //保存奖品图
    @Override
    public String savePicture(MultipartFile multipartFile) {
        //1、创建目录
        File dir=new File(localPath);
        if (!dir.exists()){
            dir.mkdirs();//创建多级目录
        }
        //2、文件命名
        //1) 获取文件名后缀名
        String filename=multipartFile.getOriginalFilename();
        assert filename!=null;
        String suffix=filename.substring(filename.lastIndexOf("."));
        //2)⽣成随机数防⽌图⽚重名
        filename= UUID.randomUUID()+suffix;

        //3、保存图片 E:/PIC/a57794e2-cb9d-475f-aa00-25c93390fcd9.jpg
        try {
            multipartFile.transferTo(new File(localPath+"/"+filename));
        } catch (IOException e) {
            throw new ServiceException(ServiceErrorCodeConstants.PIC_UPLOAD_ERROR);
        }
        return filename;
    }
}
